import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_cyber/tools/cn_common_global.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/model/cn_user_default_cache.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/pages/Mian/cn_login_page.dart';
import 'package:flutter_application_cyber/tools/cn_database_helper.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_application_cyber/model/cn_object_cache.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_application_cyber/tools/cn_log_pv_manger.dart';
class CnSettingPage extends StatefulWidget {
  const CnSettingPage({super.key});

  @override
  State<CnSettingPage> createState() => _settingState();
}

class _settingState extends State<CnSettingPage> {
  bool switcAutohValue = false;
  bool switchMessageValue = false;
  bool switchCallValue = false;
  String userId = '';

  @override
  void initState() {
    // TODO: implement initState
    // getUserData();
    super.initState();
    getUserData();
  }

  void getUserData() async {
    CnUserDefaultCacheHelper.getUserId().then((value) {
      if (value.isNotEmpty) {
        setState(() {
          userId = value;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          leading: const BackButton(color: Colors.black,),
          title: const Text(
            'Setting',
            style: TextStyle(color: Colors.black, fontSize: 18),
          ),
        ),
        body: Container(
            width: double.infinity,
            child: SafeArea(
                child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 40),
                    width: 88,
                    height: 88,
                    child: Image.asset(
                      'images/app_logo.png',
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: Text(
                      'CyberNex',
                      style: TextStyle(
                          color: Color(0xFF404040),
                          fontSize: 20,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 40),
                    height: 60,
                    child: Row(children: [
                      Expanded(
                          child: Container(
                        padding: const EdgeInsets.only(left: 16, top: 8),
                        child: Text(
                          'ID: $userId',
                          style:
                              TextStyle(fontSize: 16, color: Color(0xFF404040)),
                        ),
                      )),
                      InkWell(
                        onTap: () {
                          //复制
                          Clipboard.setData(ClipboardData(text: '$userId'));
                          EasyLoading.showSuccess('Copy successfully');
                        },
                        child: Container(
                          margin: const EdgeInsets.only(right: 20),
                          width: 42,
                          height: 20,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Color(0xFFCCCCCC),
                          ),
                          child: Text(
                            'Copy',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: 12, color: Color(0xFF565656)),
                          ),
                        ),
                      ),
                    ]),
                  ),
                  Container(
                      height: 50,
                      child: Container(
                        margin: const EdgeInsets.only(top: 10),
                        child: Row(children: [
                          Expanded(
                              child: Container(
                            padding:
                                const EdgeInsets.only(left: 16, bottom: 10),
                            child: const Text(
                              'Auto Translate',
                              style: TextStyle(
                                  fontSize: 16, color: Color(0xFF404040)),
                            ),
                          )),
                          Container(
                            padding:
                                const EdgeInsets.only(bottom: 10, right: 10),
                            child: Switch(
                                activeColor: Colors.white,
                                activeTrackColor: Color(0xFFEA248F),
                                inactiveThumbColor: Colors.white,
                                inactiveTrackColor: Colors.black,
                                value: switcAutohValue,
                                onChanged: (value) {
                                  //自动翻译
                                  setState(() {
                                    switcAutohValue = !switcAutohValue;
                                  });
                                  CnUserDefaultCacheHelper.setBoolDefault(
                                      'isAutoTranslate', value);
                                }),
                          )
                        ]),
                      )),
                  Container(
                    padding: const EdgeInsets.only(top: 100),
                    child: InkWell(
                      onTap: () {
                        EasyLoading.show(status: 'loading...');
                        CnNetHelper.logoutData((HDHResponseData configData,
                            bool result, String msg) {
                          EasyLoading.dismiss();
                          CnLogPvManger.stat(
                              page: 'logout',
                              subPage: 'subPage',
                              terPage: 'terPage',
                              broadcasterId: 'broadcasterId');

                          print(result);
                          if (result) {
                            Navigator.of(context).pushAndRemoveUntil(
                              MaterialPageRoute(
                                builder: (context) => const CnLoginPage(),
                              ),
                              (route) => false, // 这里返回false以删除所有现有的路由
                            );
                          } else {
                            EasyLoading.showError(msg);
                          }
                        });
                      },
                      child: Container(
                          margin: const EdgeInsets.only(
                              left: 12, right: 12, bottom: 30),
                          alignment: Alignment.center,
                          height: 44,
                          decoration: const BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage(
                                      'images/icon_btn_bg_comment.png'))),
                          child: Text(
                            'Logout',
                            style: TextStyle(
                              color: Color(0xff333333),
                              fontSize: 19,
                            ),
                            textAlign: TextAlign.center,
                          )),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.only(top: 10),
                    child: InkWell(
                      onTap: () {
                        _showDeleteDialog(context,
                            'Are you sure you want to delete your account?',
                            () {
                          CnNetHelper.deleteAccountData(
                              (HDHResponseData configData, bool result,
                                  String msg) async {
                            if (result) {
                              CnLogPvManger.stat(
                                  page: 'deleteaccount',
                                  subPage: 'subPage',
                                  terPage: 'terPage',
                                  broadcasterId: 'broadcasterId');

                              //清空首页数据库
                              CnDatabaseHelper.getInstance()
                                  ?.deleteAnchorRecord();
                              SharedPreferences prefs =
                                  await SharedPreferences.getInstance();
                              prefs.clear(); //清空缓存
                              CnGlobal.engine.disconnect(true); //清空融云

                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => CnLoginPage()),
                              );
                            }
                          });
                        });
                      },
                      child: Container(
                          margin: const EdgeInsets.only(
                              left: 12, right: 12, bottom: 30),
                          alignment: Alignment.center,
                          height: 44,
                          child: Text(
                            'Delete Account',
                            style: TextStyle(
                                color: Color(0x80000000),
                                fontSize: 19,
                                decoration: TextDecoration.underline,
                                decorationColor: Color(0x80000000),
                                decorationStyle: TextDecorationStyle.solid),
                            textAlign: TextAlign.center,
                          )),
                    ),
                  )
                ],
              ),
            ))));
  }
}

typedef Functiondelete<String> = void Function();
void _showDeleteDialog(context, String title, Functiondelete backBlock) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        contentPadding:
            const EdgeInsets.only(top: 24, left: 24, right: 24, bottom: 0),
        title: const Text('Confirm to delete account?'),
        content: Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              const SizedBox(height: 16),
              Text(
                title,
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 18, color: Colors.black),
              ),
              Container(
                margin: const EdgeInsets.only(top: 20, left: 0, right: 0),
                height: 1,
                color: Colors.black12,
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      child: InkWell(
                        onTap: () {
                          //复制
                          backBlock();
                          Navigator.of(context).pop();
                        },
                        child: Container(
                          height: 40,
                          alignment: Alignment.center,
                          child: const Text('Delete',
                              style:
                                  TextStyle(color: Colors.red, fontSize: 18)),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 0),
                      width: 1,
                      height: 46,
                      color: Colors.black12,
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Container(
                          height: 40,
                          alignment: Alignment.center,
                          child: const Text('Cancel',
                              style:
                                  TextStyle(color: Colors.black, fontSize: 18)),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    },
  );
}
